package com.ruoyi.web.controller.module.asset;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.asset.EstateAsset;
import com.ruoyi.system.domain.module.asset.EstateAssetExcel;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.excel.PropertyWyfTemplateExcel;
import com.ruoyi.system.domain.module.mer.Mer;
import com.ruoyi.system.service.module.asset.IEstateAssetService;
import com.ruoyi.system.service.module.estate.IEstateService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.web.controller.common.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资产管理Controller
 *
 * @author ruoyi
 * @date 2024-12-20
 */
@Validated
@Api(value = "资产管理控制器", tags = {"资产管理管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/asset")
public class AssetController extends BaseController {

    private final IEstateAssetService assetService;
	private final IEstateService estateService;
	@Value("${ruoyi.profile}")
	private String uploadPath;
    /**
     * 查询资产管理列表
     */
    @ApiOperation("查询资产管理列表")
    @PreAuthorize("@ss.hasPermi('module:asset:list')")
    @GetMapping("/list")
    public TableDataInfo<EstateAsset> list(@Validated EstateAsset estateAsset) {
        QueryWrapper<EstateAsset> qw = new QueryWrapper<>();
		if (estateAsset.getAssetName()!=null){
			qw.like("asset_name", estateAsset.getAssetName());
		}
		if (estateAsset.getAdminNickName()!=null){
			qw.like("admin_nick_name", estateAsset.getAdminNickName());
		}
		if (estateAsset.getDeviceNum()!=null){
			qw.eq("device_num", estateAsset.getDeviceNum());
		}
		if (estateAsset.getAssetType()!=null){
			qw.eq("asset_type", estateAsset.getAssetType());
		}
		if (estateAsset.getEstateId()!=null){
			qw.eq("estate_id", estateAsset.getEstateId());
		}
        TableDataInfo<EstateAsset> td = PageUtils.buildDataInfo(assetService.page(PageUtils.buildPage(),qw));
        List<EstateAsset> list = td.getRows();
		if (list.size() > 0) {
			for (EstateAsset list1 : list){
				if (list1.getEstateId() != null){
					list1.setDeviceEstateName(estateService.findById(list1.getEstateId()).getEstateName());
				}
				if (list1.getDepreciationTime() != null && list1.getProcureTime() != null){
					//对比当前日期和折旧日期
					Date now = new Date();
					if (now.after(list1.getDepreciationTime())){
						list1.setDepreciation(100.0);
					} else {
						//获取购买和折旧日期之间的天数
						Instant begin = list1.getProcureTime().toInstant();
						Instant end = list1.getDepreciationTime().toInstant();
						ZoneId zoneId = ZoneId.systemDefault();
						LocalDate beginTime = begin.atZone(zoneId).toLocalDate();
						LocalDate endTime = end.atZone(zoneId).toLocalDate();
						long baofeiDay = ChronoUnit.DAYS.between(beginTime, endTime);
						//获取当前和折旧日期之间的天数
						Instant begin_now = now.toInstant();
						Instant end_now = list1.getDepreciationTime().toInstant();
						ZoneId zoneIds = ZoneId.systemDefault();
						LocalDate beginTimes = begin_now.atZone(zoneId).toLocalDate();
						LocalDate endTimes = end_now.atZone(zoneId).toLocalDate();
						long shiyongDay = ChronoUnit.DAYS.between(beginTimes, endTimes);
						list1.setDepreciation(Double.valueOf(100 - shiyongDay * 100 / baofeiDay));
					}
				}
			}
		}
        return td;
    }

    /**
     * 导出资产管理列表
     */
    @ApiOperation("导出资产管理列表")
    @PreAuthorize("@ss.hasPermi('module:asset:export')")
    @Log(title = "资产管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EstateAsset> export(@Validated EstateAsset estateAsset) {
        List<EstateAsset> list = assetService.list();
        ExcelUtil<EstateAsset> util = new ExcelUtil<EstateAsset>(EstateAsset.class);
        return util.exportExcel(list, "资产管理");
    }

	@Log(title = "资产导入", businessType = BusinessType.IMPORT)
	@PreAuthorize("@ss.hasAnyPermi('module:asset:import')")
	@PostMapping("/import")
	public AjaxResult importDataAsset(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtil<EstateAssetExcel> util = new ExcelUtil<>(EstateAssetExcel.class);
		List<EstateAssetExcel> templateExcels = util.importExcel(file.getInputStream());
		SysUser sysUser = getUser();
		String operName = sysUser.getUserName();
		String message = assetService.importAssetData(templateExcels, updateSupport, operName);
		return AjaxResult.success(message);
	}


    /**
     * 获取资产管理详细信息
     */
    @ApiOperation("获取资产管理详细信息")
    @PreAuthorize("@ss.hasPermi('module:asset:query')")
    @GetMapping("/{id}")
    public AjaxResult<EstateAsset> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateAsset estateAsset = assetService.getById(id);
        return AjaxResult.success(estateAsset);
    }


	/**
	 * 固定资产二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetGudingCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:asset:edit')")
	public AjaxResult<Void> resetGudingCode(@RequestBody EstateAsset estateAsset) {
		if(estateAsset.getId()!=null){
			try{
				estateAsset = assetService.getById(estateAsset.getId());
				if(estateAsset != null){
					String fileName = "asset_qr_" + estateAsset.getAssetName() + ".jpg";
					String content = "https://www.caihengyun.com/wxmini/asset/check/?id=" + estateAsset.getId();
					int upload_type = FileUploadUtils.TYPE_GUDING_ASSET_QR_CODE;
					System.out.println("content:  "+ content);
					String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, estateAsset.getAssetName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
					estateAsset.setQrCode(img_key);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (assetService.updateById(estateAsset)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

	/**
	 * 移动资产二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetYidongCord")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:asset:edit')")
	public AjaxResult<Void> resetYidongCord(@RequestBody EstateAsset estateAsset) {
		if(estateAsset.getId()!=null){
			try{
				estateAsset = assetService.getById(estateAsset.getId());
				if(estateAsset != null){
					String fileName = "asset_qr_" + estateAsset.getAssetName() + ".jpg";
					String content = "https://www.caihengyun.com/wxmini/asset/borrow/?id=" + estateAsset.getId();
					int upload_type = FileUploadUtils.TYPE_YIDONG_ASSET_QR_CODE;
					System.out.println("content:  "+ content);
					String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, estateAsset.getAssetName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
					estateAsset.setQrCode(img_key);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (assetService.updateById(estateAsset)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}

    /**
     * 新增资产管理
     */
    @ApiOperation("新增资产管理")
    @PreAuthorize("@ss.hasPermi('module:asset:add')")
    @Log(title = "资产管理", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EstateAsset estateAsset) {
		estateAsset.setState(0);
		Boolean b = assetService.save(estateAsset);
		if (estateAsset.getDeviceNum()==null){
			if (estateAsset.getDeviceType()==0){
				estateAsset.setDeviceNum("bg-00"+ estateAsset.getId());
			}
		}
		if(estateAsset.getEstateId()!=null){
			Estate estate = estateService.findById(estateAsset.getEstateId());
			if (estate!=null){
				if (estate.getPropertyId()!=null){
					estateAsset.setPropertyId(estate.getPropertyId());
				}
			}
		}
		if (b){
			b = assetService.updateById(estateAsset);
		}
        return toAjax(b ? 1 : 0);
    }

    /**
     * 修改资产管理
     */
    @ApiOperation("修改资产管理")
    @PreAuthorize("@ss.hasPermi('module:asset:edit')")
    @Log(title = "资产管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EstateAsset estateAsset) {
        return toAjax(assetService.updateById(estateAsset) ? 1 : 0);
    }

    /**
     * 删除资产管理
     */
    @ApiOperation("删除资产管理")
    @PreAuthorize("@ss.hasPermi('module:asset:remove')")
    @Log(title = "资产管理" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(assetService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
